package gui.VPOfOperations;

import entities.ProductionOrder;
import entities.RequestParameters;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Date;
import java.text.DecimalFormat;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;

import net.miginfocom.swing.MigLayout;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;

import table.model.EnvelopeTableModel;
import table.model.demo.ColumnSelectorControl;
import table.model.exception.GroupException;
import table.model.renderer.CrossTabRenderer;
import table.model.renderer.NumberRenderer;
import table.model.renderer.SimpleRenderer;
import utilities.PrintActionListener;

import javax.swing.ImageIcon;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import java.awt.Font;

/**
 * @author Idan
 *Report GUI
 */
public class VPOfOperationsFailQuantitiesByQCMonthReport extends JPanel 
{
	private JPanel mainPanel;
	private JTable myTable;
	private JScrollPane myScroll;
	private JScrollPane chartTableScroll;
	private EnvelopeTableModel model;
	private TableModel originalModel;
	private DefaultCategoryDataset dataset ;
	private VPOfOperationsTabbedPane tabbedpane;
	
	public VPOfOperationsFailQuantitiesByQCMonthReport (VPOfOperationsTabbedPane myTabbedPane, RequestParameters parameters) 
	{
		setBackground(new Color(173, 216, 230));
		this.tabbedpane = myTabbedPane;
		setLayout(new MigLayout("", "[][grow][]", "[][grow][][]"));
		
		mainPanel = new JPanel(){	@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		mainPanel.setBackground(new Color(173, 216, 230));
		mainPanel.setBorder(new TitledBorder(null, "\u05D3\u05D5\u05D7 \u05E4\u05E1\u05D9\u05DC\u05D5\u05EA \u05E2\u05DC \u05E4\u05D9 \u05D7\u05D5\u05D3\u05E9 \u05D1\u05D3\u05D9\u05E7\u05D4 " + new Date(parameters.getStartTimestamp().getTime()) + " - " + new Date(parameters.getEndTimestamp().getTime()), TitledBorder.CENTER, TitledBorder.TOP, null, new Color(59, 59, 59)));
		add(mainPanel, "cell 1 1,growx,aligny center");
		mainPanel.setLayout(new MigLayout("", "[][grow][]", "[][::200px][grow][]"));
		
		
	
		
		JButton closeButton = new JButton("סגור דוח");
		closeButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		closeButton.setIcon(new ImageIcon(VPOfOperationsFailQuantitiesByQCMonthReport.class.getResource("/graphics/back.png")));
		closeButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0)
			{
				// get tab index
				tabbedpane.remove(tabbedpane.getSelectedIndex());
				// remove tab
			}
		});
		add(closeButton, "flowx,cell 1 2,alignx center");
		
		JLabel lblNewLabel = new JLabel("               ");
		add(lblNewLabel, "cell 1 2");
		
		JButton printButton = new JButton("יצא לאקסל");
		printButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		printButton.setIcon(new ImageIcon(VPOfOperationsFailQuantitiesByQCMonthReport.class.getResource("/graphics/excel.png")));
		printButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e)
			{
JTable table = utilities.Services.parsePivotTableToJTrable(myTable);
				
				ArrayList<Object> result = utilities.Services.exportToExcel(table);
				if (result.get(0).equals(true))
				{
					// confirm
					JOptionPane.showMessageDialog(mainPanel,
							result.get(1).toString() + " :הדוח נשמר " ,"אישור",JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					// error
					JOptionPane.showMessageDialog(mainPanel,
						    "לא ניתן לשמור את הדוח.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
				//new Thread(new PrintActionListener(mainPanel)).start();   
			}
		});
		add(printButton, "cell 1 2,alignx center");
		
		
		  
	}
	
	public void setVariables(ArrayList<Object> response) 
	{
		// index 0 is the flag
		// index 1 is the counter
		// index 2 and onwards is the data

		originalModel=getModel(response);
		
		  model=new EnvelopeTableModel(originalModel);
		  myTable=new JTable(model);
		  
		
		  
		  myTable.setDefaultRenderer(String.class,new SimpleRenderer(true));
		  myTable.setDefaultRenderer(Date.class,new SimpleRenderer(true));
		  myTable.setDefaultRenderer(Object.class,new SimpleRenderer(true));
		  
		  myTable.setDefaultRenderer(Double.class,new NumberRenderer(true));
		  myTable.setDefaultRenderer(Float.class,new NumberRenderer(true));
		  myTable.setDefaultRenderer(Integer.class,new NumberRenderer(true));
		  myTable.setDefaultRenderer(Long.class,new NumberRenderer(true));
		  showDefaultCross();	
		  
		  
		  myScroll=new JScrollPane(myTable);
		  mainPanel.add(myScroll, "cell 1 1,grow");
		  
		  // try and get data from the new model
		  TableModel pivotModel= myTable.getModel();
		  int countRow = pivotModel.getRowCount();
		  int countCol = pivotModel.getColumnCount();
		  
		  int rowStart = 1;
		  int rowEnd = countRow-1;
		  
		  int colStart = 1;
		  int colEnd = countCol-1;
		  
		  
		  
		  // initialize Dataset
		  
		  dataset = new DefaultCategoryDataset();
		  
		  for (rowStart=1; rowStart<rowEnd;rowStart++)
		  {
			  for (colStart=1 ;colStart<colEnd ;colStart++)
			  {
				  // pivotTable might return null when there's no value
				  Number count =0;
				  //	System.out.println("Accessing row = " + rowStart + " col = " + colStart);
				  try
				  {
					  count = (Number) pivotModel.getValueAt(rowStart, colStart);
				  }
				  catch (ClassCastException e)
				  {
					  count = 0;
				  }
		       		
		        		
				  String product = pivotModel.getValueAt(0, colStart).toString();
				  String diopter = pivotModel.getValueAt(rowStart, 0).toString();
				  //	System.out.println("Count = " + count + " Product = " + product + " Diopter = " + diopter);		        		
		        		
				  dataset.addValue(count,product,diopter);
		        		
		        		
		        		
			  }
		        	
		  }
		        
		        
		  // create Chart
		        
		      
		  //  JFreeChart chart = ChartFactory.createBarChart(
		  JFreeChart chart = ChartFactory.createStackedBarChart3D(
				  ((TitledBorder)mainPanel.getBorder()).getTitle(), // chart title
				  "חודש", // domain axis label
				  "פסילות", // range axis label
				  dataset, // data
				  PlotOrientation.VERTICAL, // orientation
				  true, // include legend
				  true, // tooltips?
				  false // URLs?
				  );

		        
		    
		  final CategoryPlot plot = (CategoryPlot) chart.getPlot();
		  BarRenderer renderer =  (BarRenderer) plot.getRenderer();
		  DecimalFormat format = new DecimalFormat("##.#");
		  renderer.setItemLabelGenerator((CategoryItemLabelGenerator) new StandardCategoryItemLabelGenerator("{2}",format));
		  renderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_CENTER));
		  renderer.setItemLabelsVisible(true);
		        
		  CategoryAxis xAxis = (CategoryAxis)plot.getDomainAxis();
	      xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);    
		        
//		        renderer.setSeriesItemLabelsVisible(0, true);

		        //renderer.
		        // renderer.setItemMargin(0.0);
		        
		        
		  ChartPanel chartPanel = new ChartPanel(chart, false);
		  chartPanel.setMouseWheelEnabled(true);
		      //  chartPanel.setPreferredSize(new Dimension(500, 270));
		        
		  chartTableScroll = new JScrollPane(chartPanel);
		  mainPanel.add(chartTableScroll, "cell 1 2,grow");
		       // mainPanel.add(chartPanel, "cell 1 2,grow");
		       // chartPanel.setVisible(true);
		        

		
		
	}

	

	
	
	 public TableModel getModel(ArrayList<Object> response)
	 {
		 
	        Object[][] ss=new Object[response.size()-2][5];
	       
	        
	        for (int i=1; i<=((int)response.get(1));i++)
	        {
	        	
	        	ProductionOrder report = (ProductionOrder)response.get(i+1);	       
	        	ss[i-1] = new Object[]{report.getQuantity(),Integer.parseInt(report.getFails()),report.getProductFamily(),report.getDateAsMonthYear(),report.getOrderID()};
	        //	System.out.println("DATA : " + report.getQuantity() + " " + Integer.parseInt(report.getFails()) + " " + report.getProductFamily() + " " + report.getQcDateMonthAndYearAsString() + " " + report.getOrderID());
	        }
	        
	       
	        FailQuantitiesReportTable dm= new FailQuantitiesReportTable(ss,new String[] {"Quantity","Fails","ProductFamily","Quality Control Date","OrderID"});
	        return dm;
	    }
	 
	 
	 
	
	 public void showDefaultCross()
	 {
		 
		 
	        try
	        {
	            model.reset();
	        
	            int[] sortColumnIndexes=new int[] {3};
	   		 	boolean[] sortOrders=new boolean[] {true};
	   		 	
	   		// model.setSort(sortColumnIndexes,sortOrders);
	   		 
	   		 	
	   		 /*	int[] groupColumnIndexes=new int[] {1,2};
	   		 	boolean[] groupOrders=new boolean[] {true,true};

	   	  
	   		 	

	   		*/
	   		 	
	   		 //int count=myTable.getColumnCount();
	   		
           //  int[] groupColumnIndexes = new int[] {3,2};   
          //   boolean[]  groupOrders = new boolean[] {true,true};
        /*     try
             {
              //   model.setGroup(groupColumnIndexes,groupOrders);
            //     model.setGroupFunction(0,EnvelopeTableModel.GROUP_FUNCTION_SUM);
           //      model.setGroupFunction(1,EnvelopeTableModel.GROUP_FUNCTION_SUM);
   
                
               //  count=model.getColumnCount();
//                 restoreNormalColumnModel();
             }
             catch (GroupException ex) 
             {
                 JOptionPane.showMessageDialog(null,ex.getMessage());
             }
          */   
	   	      
	            myTable.setDefaultRenderer(Object.class,new CrossTabRenderer());
	            model.setCrossTab(3,true,2,true,1);

	          
	            
	            
	            model.setCrossTabFunction(EnvelopeTableModel.GROUP_FUNCTION_SUM,EnvelopeTableModel.DIRECTION_HORIZONTAL);
	            model.setCrossTabFunction(EnvelopeTableModel.GROUP_FUNCTION_SUM,EnvelopeTableModel.DIRECTION_VERTICAL);
	            myTable.setTableHeader(null);
	            myTable.tableChanged(new TableModelEvent(model,TableModelEvent.HEADER_ROW));
	            myTable.setShowGrid(true);
	            myTable.setShowHorizontalLines(true);
	            myTable.setShowVerticalLines(true);
	            
	            myTable.setBorder(new TitledBorder(null, "", TitledBorder.RIGHT, TitledBorder.ABOVE_TOP, null, null));
	            
	            if (myScroll!=null)
	                myScroll.setColumnHeader(null);

	    }
	        catch (Exception ex) {
	            ex.printStackTrace();
	        }
	    }
	 
		@Override
		public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Color color1 = getBackground();
        Color color2 = color1.darker();
        int w = getWidth();
        int h = getHeight(); 
        GradientPaint gp = new GradientPaint(
                0, 0, color1,
                0, h, color2);

        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        }
	 
}